<template>
  <div class="restricted-archive-request-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>受限档案申请管理</span>
        <div class="header-buttons">
          <el-button type="primary" @click="showSubmitDialog" v-if="userRole === '普通员工'">
            <i class="el-icon-plus"></i>
            申请查看受限档案
          </el-button>
          <el-button type="info" @click="loadRequests">
            <i class="el-icon-refresh"></i>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="search-bar">
        <el-select v-model="searchStatus" placeholder="按状态筛选" clearable @change="loadRequests" style="width: 150px;">
          <el-option label="待审批" value="pending"></el-option>
          <el-option label="已批准" value="approved"></el-option>
          <el-option label="已拒绝" value="rejected"></el-option>
        </el-select>
        <el-input 
          placeholder="搜索档案标题、申请原因或申请人" 
          v-model="searchQuery" 
          class="input-with-select" 
          @keyup.enter.native="loadRequests"
          style="width: 300px; margin-left: 10px;">
          <el-button slot="append" icon="el-icon-search" @click="loadRequests"></el-button>
        </el-input>
      </div>

      <!-- 申请列表 -->
      <el-table :data="requests" style="width: 100%" v-loading="loading">
        <el-table-column prop="requestId" label="申请ID" width="80"></el-table-column>
        <el-table-column prop="archiveTitle" label="档案标题" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="archiveType" label="档案类型" width="120"></el-table-column>
        <el-table-column prop="securityLevel" label="保密等级" width="100">
          <template slot-scope="scope">
            <el-tag :type="getSecurityLevelType(scope.row.securityLevel)">
              {{ scope.row.securityLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="申请人" width="120"></el-table-column>
        <el-table-column prop="reason" label="申请原因" show-overflow-tooltip></el-table-column>
        <el-table-column prop="expectedDuration" label="预计使用期限" width="130"></el-table-column>
        <el-table-column prop="requestTime" label="申请时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.requestTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="approvalStatus" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.approvalStatus)">
              {{ getStatusText(scope.row.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="viewRequest(scope.row)">查看</el-button>
            <el-button 
              size="mini" 
              type="primary" 
              @click="approveRequest(scope.row)" 
              v-if="userRole === '企业领导' && scope.row.approvalStatus === 'pending'">
              审批
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next">
      </el-pagination>
    </el-card>

    <!-- 提交申请对话框 -->
    <el-dialog title="申请查看受限档案" :visible.sync="submitDialogVisible" width="600px">
      <el-form :model="requestForm" :rules="requestRules" ref="requestForm">
        <el-form-item label="选择档案" prop="archiveId">
          <el-select 
            v-model="requestForm.archiveId" 
            placeholder="请选择要申请查看的受限档案" 
            style="width: 100%"
            filterable
            @change="handleArchiveChange">
            <el-option
              v-for="archive in restrictedArchives"
              :key="archive.archiveId"
              :label="`${archive.title} (${archive.securityLevel})`"
              :value="archive.archiveId">
              <span style="float: left">{{ archive.title }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ archive.securityLevel }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        
        <!-- 显示选中档案的详细信息 -->
        <div v-if="selectedArchive" class="selected-archive-info">
          <h4>档案详情</h4>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="档案标题">{{ selectedArchive.title }}</el-descriptions-item>
            <el-descriptions-item label="档案类型">{{ selectedArchive.archiveType }}</el-descriptions-item>
            <el-descriptions-item label="保密等级">
              <el-tag :type="getSecurityLevelType(selectedArchive.securityLevel)">
                {{ selectedArchive.securityLevel }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="物理位置">{{ selectedArchive.physicalLocation || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <el-form-item label="申请原因" prop="reason">
          <el-input 
            type="textarea" 
            :rows="4" 
            v-model="requestForm.reason" 
            placeholder="请详细说明申请查看该受限档案的原因和用途">
          </el-input>
        </el-form-item>
        <el-form-item label="预计使用期限" prop="expectedDuration">
          <el-select v-model="requestForm.expectedDuration" placeholder="请选择预计使用期限">
            <el-option label="1天" value="1天"></el-option>
            <el-option label="3天" value="3天"></el-option>
            <el-option label="1周" value="1周"></el-option>
            <el-option label="2周" value="2周"></el-option>
            <el-option label="1个月" value="1个月"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-alert
          title="提示：受限档案申请需要企业领导审批，审批通过后方可查看"
          type="info"
          :closable="false"
          show-icon>
        </el-alert>
      </el-form>
      <div slot="footer">
        <el-button @click="submitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRequest">提交申请</el-button>
      </div>
    </el-dialog>

    <!-- 查看申请详情对话框 -->
    <el-dialog title="申请详情" :visible.sync="viewDialogVisible" width="700px">
      <div v-if="currentRequest">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请ID">{{ currentRequest.requestId }}</el-descriptions-item>
          <el-descriptions-item label="档案标题">{{ currentRequest.archiveTitle }}</el-descriptions-item>
          <el-descriptions-item label="档案类型">{{ currentRequest.archiveType }}</el-descriptions-item>
          <el-descriptions-item label="保密等级">
            <el-tag :type="getSecurityLevelType(currentRequest.securityLevel)">
              {{ currentRequest.securityLevel }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentRequest.userName }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(currentRequest.requestTime) }}</el-descriptions-item>
          <el-descriptions-item label="预计使用期限">{{ currentRequest.expectedDuration }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRequest.approvalStatus)">
              {{ getStatusText(currentRequest.approvalStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请原因" :span="2">
            <div style="max-height: 100px; overflow-y: auto;">
              {{ currentRequest.reason }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="审批人" v-if="currentRequest.approverName">
            {{ currentRequest.approverName }}
          </el-descriptions-item>
          <el-descriptions-item label="审批时间" v-if="currentRequest.approvalTime">
            {{ formatDate(currentRequest.approvalTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="审批备注" :span="2" v-if="currentRequest.notes">
            <div style="max-height: 100px; overflow-y: auto;">
              {{ currentRequest.notes }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="审批申请" :visible.sync="approveDialogVisible" width="500px">
      <el-form :model="approveForm" ref="approveForm">
        <el-form-item label="审批决定">
          <el-radio-group v-model="approveForm.approvalStatus">
            <el-radio label="approved">批准</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批备注">
          <el-input 
            type="textarea" 
            :rows="4" 
            v-model="approveForm.notes" 
            placeholder="请输入审批意见或备注">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApproval">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'RestrictedArchiveRequest',
  data() {
    return {
      requests: [],
      restrictedArchives: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userRole: '',
      userId: null,
      searchStatus: '',
      searchQuery: '',
      submitDialogVisible: false,
      viewDialogVisible: false,
      approveDialogVisible: false,
      currentRequest: null,
      selectedArchive: null,
      requestForm: {
        archiveId: '',
        reason: '',
        expectedDuration: ''
      },
      requestRules: {
        archiveId: [
          { required: true, message: '请选择档案', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请输入申请原因', trigger: 'blur' },
          { min: 10, message: '申请原因不能少于10个字符', trigger: 'blur' }
        ],
        expectedDuration: [
          { required: true, message: '请选择预计使用期限', trigger: 'change' }
        ]
      },
      approveForm: {
        approvalStatus: 'approved',
        notes: ''
      }
    }
  },
  created() {
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    if (user && user.role) {
      this.userRole = user.role;
      this.userId = user.userId;
    }
  },
  mounted() {
    this.loadRequests();
    this.loadRestrictedArchives();
  },
  methods: {
    async loadRequests() {
      this.loading = true;
      try {
        const response = await service.get('/restricted-archive-request/list', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            status: this.searchStatus,
            search: this.searchQuery
          }
        });
        if (response.data.code === 200) {
          this.requests = response.data.data.records;
          this.total = response.data.data.total;
        } else {
          this.$message.error(response.data.message);
        }
      } catch (error) {
        console.error('获取申请列表失败', error);
        this.$message.error('获取申请列表失败');
      } finally {
        this.loading = false;
      }
    },

    async loadRestrictedArchives() {
      try {
        const response = await service.get('/archive/list', {
          params: {
            pageNum: 1,
            pageSize: 9999
          }
        });
        if (response.data.code === 200) {
          // 过滤出受限档案（保密等级不是公开的档案）
          this.restrictedArchives = response.data.data.records.filter(archive => 
            archive.securityLevel && archive.securityLevel !== '公开'
          );
        }
      } catch (error) {
        console.error('获取受限档案列表失败', error);
      }
    },

    showSubmitDialog() {
      this.submitDialogVisible = true;
      this.resetRequestForm();
    },

    handleArchiveChange(archiveId) {
      const archive = this.restrictedArchives.find(item => item.archiveId === archiveId);
      this.selectedArchive = archive || null;
    },

    async submitRequest() {
      this.$refs.requestForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await service.post('/restricted-archive-request/submit', this.requestForm);
            if (response.data.code === 200) {
              this.$message.success('申请提交成功');
              this.submitDialogVisible = false;
              this.loadRequests();
            } else {
              this.$message.error(response.data.message);
            }
          } catch (error) {
            this.$message.error('申请提交失败');
          }
        }
      });
    },

    viewRequest(request) {
      this.currentRequest = request;
      this.viewDialogVisible = true;
    },

    approveRequest(request) {
      this.currentRequest = request;
      this.approveForm = {
        approvalStatus: 'approved',
        notes: ''
      };
      this.approveDialogVisible = true;
    },

    async submitApproval() {
      try {
        const response = await service.put(
          `/restricted-archive-request/approve/${this.currentRequest.requestId}`,
          null,
          {
            params: {
              approvalStatus: this.approveForm.approvalStatus,
              notes: this.approveForm.notes
            }
          }
        );
        if (response.data.code === 200) {
          this.$message.success('审批成功');
          this.approveDialogVisible = false;
          this.loadRequests();
        } else {
          this.$message.error(response.data.message);
        }
      } catch (error) {
        this.$message.error('审批失败');
      }
    },

    resetRequestForm() {
      this.requestForm = {
        archiveId: '',
        reason: '',
        expectedDuration: ''
      };
      this.selectedArchive = null;
      if (this.$refs.requestForm) {
        this.$refs.requestForm.resetFields();
      }
    },

    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadRequests();
    },

    formatDate(dateString) {
      if (!dateString) return '';
      return new Date(dateString).toLocaleString('zh-CN');
    },

    getStatusType(status) {
      const typeMap = {
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'danger'
      };
      return typeMap[status] || 'info';
    },

    getStatusText(status) {
      const textMap = {
        'pending': '待审批',
        'approved': '已批准',
        'rejected': '已拒绝'
      };
      return textMap[status] || status;
    },

    getSecurityLevelType(level) {
      const typeMap = {
        '绝密': 'danger',
        '机密': 'warning',
        '秘密': 'primary',
        '内部': 'info',
        '公开': 'success'
      };
      return typeMap[level] || 'info';
    }
  }
}
</script>

<style scoped>
.restricted-archive-request-container {
  padding: 20px;
}

.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.selected-archive-info {
  margin: 15px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.selected-archive-info h4 {
  margin-bottom: 15px;
  color: #606266;
}

.box-card {
  width: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.box-card .el-card__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom: none;
}

.box-card .el-card__header .clearfix span {
  font-size: 16px;
  font-weight: 500;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style> 